package com.openway.game;

import com.openway.game.field.Coordinate;
import com.openway.game.field.Direction;
import com.openway.game.personage.impl.Drunkard;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 * This class represents work of the police station - to give the task to policeman.
 *
 * @author Created: 04.03.12 13:22
 * @version $Date$ $Revision$
 */
public class PoliceStation {
    public static final Coordinate INITIAL_POLICEMAN_COORDINATE = new Coordinate(3, 14);

    private Queue<Drunkard> drunkardsToTakeAway;

    public PoliceStation() {
        initDrunkardsToTakeAwayQueue();
    }

    /**
     * Obtains the next sleeping drunkard who must be taken away.
     *
     * @return Drunkard to take away or null if no such
     */
    public Drunkard getDrunkardToTakeAway() {
        return drunkardsToTakeAway.poll();
    }

    /**
     * Add new drunkard to those who should be taken away.
     * This realization adds sleeping and lighted drunkards, and skips others.
     *
     * @param drunkard drunkard to analyze
     * @return true if drunkard is added, false otherwise
     */
    public boolean addToTakenAwayIfNeeded(Drunkard drunkard) {
        if (drunkard.isSleeping() && Game.getInstance().getPlayingField().isLighted(drunkard)) {
            drunkardsToTakeAway.add(drunkard);
            return true;
        }
        return false;
    }

    //policeman take away nearest sleeping drunkard
    private void initDrunkardsToTakeAwayQueue() {
        drunkardsToTakeAway = new PriorityQueue<Drunkard>(11, new Comparator<Drunkard>() {
            @Override
            public int compare(Drunkard o1, Drunkard o2) {
                Coordinate o1Coordinate = Game.getInstance().getPlayingField().getObjectCoordinate(o1);
                Coordinate o2Coordinate = Game.getInstance().getPlayingField().getObjectCoordinate(o2);

                Integer o1Distance = Math.abs(o1Coordinate.getColumn() - INITIAL_POLICEMAN_COORDINATE.getColumn()) +
                        Math.abs(o1Coordinate.getRow() - INITIAL_POLICEMAN_COORDINATE.getRow());
                Integer o2Distance = Math.abs(o2Coordinate.getColumn() - INITIAL_POLICEMAN_COORDINATE.getColumn()) +
                        Math.abs(o2Coordinate.getRow() - INITIAL_POLICEMAN_COORDINATE.getRow());
                return o1Distance.compareTo(o2Distance);
            }
        });
    }
}
